using System;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using System.Drawing;

namespace GameOfLifeX.IOS.Client
{
	public class MyView : UIView
	{
		public MyView (int width, int height)
		{
			_width = width;
			_height = height;
			_bytesPerRow = _bytesPerPixel * _width;
			_widthTimesHeight = _width * height;
			_widthTimesHeightTimesBytesPerPixel = _widthTimesHeight * _bytesPerPixel;
			UserInteractionEnabled = true;
		}

		private readonly int _bytesPerPixel = 3;
		private readonly int _widthTimesHeight;
		private readonly int _widthTimesHeightTimesBytesPerPixel;
		private readonly int _bitsPerComponent = 8;
		private readonly int _bitsPerPixel = 24;
		private readonly CGColorSpace _colorSpace = CGColorSpace.CreateDeviceRGB ();
		private readonly CGBitmapFlags _bitmapFlags = CGBitmapFlags.ByteOrderDefault;
		private readonly CGColorRenderingIntent _colorRenderingIntent = CGColorRenderingIntent.Default;
		private readonly int _bytesPerRow;
		private CGImage _image;
		private readonly int _width;
		private readonly int _height;
		private byte[] _bytes;

		private void InitializeImage (byte[] bytes)
		{		
			var cgDataProvider = new CGDataProvider (bytes, 0, _widthTimesHeight);
			_image = new CGImage (_width, _height, _bitsPerComponent, _bitsPerPixel, _bytesPerRow, _colorSpace, _bitmapFlags, cgDataProvider, null, false, _colorRenderingIntent);
		}

		public void RenderCells (bool[,] cells)
		{
			if (_bytes == null)
				_bytes = new byte[_widthTimesHeightTimesBytesPerPixel];

			int offset = 0;


			//for (int y = 0; y < _height; y++)
			for (int y = _height-1; y >=0 ; y--)
				for (int x = 0; x < _width; x++)
				{

					var alive = cells [x, y];
					int index = offset;
					_bytes [index] = alive ? (byte)255 : (byte)Math.Max (0, _bytes [index] - 10);
					offset++;

					index = offset;
					_bytes [index] = alive ? (byte)255 : (byte)Math.Max (0, _bytes [index] - 5);
					offset++;

					index = offset;
					_bytes [index] = alive ? (byte)255 : (byte)Math.Max (0, _bytes [index] - 2);
					offset++;
				}

			InitializeImage (_bytes);
			SetNeedsDisplay ();
		}

		public override void TouchesBegan (NSSet touches, UIEvent evt)
		{
			base.TouchesBegan (touches, evt);

			UITouch touch = touches.AnyObject as UITouch;
			if (touch != null)
			{
				LastTouch = touch;
			}
		}	

		public UITouch LastTouch{ get; set;}

		public override void TouchesMoved (NSSet touches, UIEvent evt)
		{
			base.TouchesMoved (touches, evt);

			UITouch touch = touches.AnyObject as UITouch;
			if (touch != null)
			{
				LastTouch = touch;
			}
		}

		public override void TouchesEnded (NSSet touches, UIEvent evt)
		{
			base.TouchesEnded (touches, evt);
		}

		public override void Draw (RectangleF rect)
		{
			base.Draw (rect);

			using (CGContext context = UIGraphics.GetCurrentContext ())
			{						
				if (_image != null)
					context.DrawImage (rect, _image);
			}
		}
	}
}

